part of '../repository.dart';

const _kUseCaseExampleMarkdownKey = 'example_markdown';
const _kUseCaseTranslationMarkdownsKey = 'translation_markdowns';

class _UseCaseDto extends Equatable {
  const _UseCaseDto._internal({
    required this.exampleMarkdown,
    required this.translationMarkdownDtoMap,
  });

  final String exampleMarkdown;
  final BuiltMap<_LearningLocaleDto, String> translationMarkdownDtoMap;

  @override
  List<Object?> get props {
    return [
      exampleMarkdown,
      translationMarkdownDtoMap,
    ];
  }

  factory _UseCaseDto.fromJson(Map<String, dynamic> json) {
    final translationMarkdownMap = json[_kUseCaseTranslationMarkdownsKey] as Map;

    final translationMarkdownDtoMap =
        translationMarkdownMap.map((learningLocaleString, translationMarkdown) {
      final learningLocaleDto = _LearningLocaleDto.fromString(learningLocaleString);
      return MapEntry(learningLocaleDto, translationMarkdown as String);
    }).build();

    return _UseCaseDto._internal(
      exampleMarkdown: json[_kUseCaseExampleMarkdownKey],
      translationMarkdownDtoMap: translationMarkdownDtoMap,
    );
  }

  factory _UseCaseDto.fromEntity(LexicalItemUseCase useCase) {
    final translationMarkdownDtoMap =
        useCase.translationMarkdowns.map((learningLocale, translationMarkdown) {
      final learningLocaleDto = _LearningLocaleDto.fromEntity(learningLocale);
      return MapEntry(learningLocaleDto, translationMarkdown);
    });

    return _UseCaseDto._internal(
      exampleMarkdown: useCase.exampleMarkdown,
      translationMarkdownDtoMap: translationMarkdownDtoMap,
    );
  }

  Map<String, dynamic> toJson() {
    final translationMarkdownJson =
        translationMarkdownDtoMap.map((learningLocaleDto, translationMarkdown) {
      return MapEntry(learningLocaleDto.toString(), translationMarkdown);
    }).toMap();

    return {
      _kUseCaseExampleMarkdownKey: exampleMarkdown,
      _kUseCaseTranslationMarkdownsKey: translationMarkdownJson,
    };
  }

  LexicalItemUseCase toEntity() {
    final translationMarkdowns =
        translationMarkdownDtoMap.map((learningLocaleDto, translationMarkdown) {
      return MapEntry(learningLocaleDto.toEntity(), translationMarkdown);
    });

    return LexicalItemUseCase(
      exampleMarkdown: exampleMarkdown,
      translationMarkdowns: translationMarkdowns,
    );
  }
}
